import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:permission_handler/permission_handler.dart';
import 'dart:async';
import 'dart:io';

import '../pages/device_detail_page.dart';

/// BLE扫描页面
/// 负责扫描和显示可用的BLE设备
class BleScannerPage extends StatefulWidget {
  const BleScannerPage({super.key});

  @override
  State<BleScannerPage> createState() => _BleScannerPageState();
}

class _BleScannerPageState extends State<BleScannerPage> {
  List<ScanResult> scanResults = [];
  bool isScanning = false;
  StreamSubscription? scanSubscription;
  StreamSubscription<BluetoothAdapterState>? _adapterStateSub;
  BluetoothAdapterState _adapterStateNow = BluetoothAdapterState.unknown;

  @override
  void initState() {
    super.initState();
    // 监听蓝牙适配器状态变化，并打印详细日志
    _adapterStateSub = FlutterBluePlus.adapterState.listen((state) {
      _adapterStateNow = state;
      debugPrint('[BLE] Adapter state changed: $state');
      if (state != BluetoothAdapterState.on) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('蓝牙未启用或不可用，请开启蓝牙')),
        );
      }
    });

    // iOS: 不依赖 permission_handler 的蓝牙权限；依赖适配器状态
    // Android: 初始化时请求位置权限
    _requestPermissionsOnInit();
  }
  
  void _requestPermissionsOnInit() async {
    if (Platform.isIOS) {
      // iOS 13+/14+：扫描不再需要位置权限，也无专门的“蓝牙权限弹窗”
      // 我们仅依赖 FlutterBluePlus.adapterState 监听是否 PoweredOn
      debugPrint('[BLE] iOS initialization: relying on CBCentralManager state, not requesting Permission.bluetooth');
    } else {
      final status = await Permission.location.request();
      debugPrint('[BLE] Initial permission request -> location: $status');
      if (status != PermissionStatus.granted) {
        debugPrint('[BLE] 位置权限未授予');
      }
    }
  }

  @override
  void dispose() {
    _stopScan();
    _adapterStateSub?.cancel();
    super.dispose();
  }

  Future<bool> _ensurePermissionsAndBluetoothOn() async {
    // iOS: 不做蓝牙权限检查，直接依赖适配器状态为 ON
    if (!Platform.isIOS) {
      final locStatus = await Permission.location.status;
      debugPrint('[BLE] Current location permission status: $locStatus');
      if (!locStatus.isGranted) {
        final req = await Permission.location.request();
        debugPrint('[BLE] Request location permission -> $req');
        if (!req.isGranted) {
          if (req.isPermanentlyDenied) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('位置权限被拒绝，请到系统设置中启用权限')),
            );
            await openAppSettings();
          }
          return false;
        }
      }
    }

    // 等待蓝牙适配器变为 ON（iOS 无法代码开启，需要用户）
    try {
      if (_adapterStateNow != BluetoothAdapterState.on) {
        debugPrint('[BLE] Waiting for adapter to be ON ...');
        _adapterStateNow = await FlutterBluePlus.adapterState
            .firstWhere((s) => s == BluetoothAdapterState.on)
            .timeout(const Duration(seconds: 10));
      }
      debugPrint('[BLE] Adapter is ON, ready to scan');
      return true;
    } catch (e) {
      debugPrint('[BLE] Adapter did not turn ON in time: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('蓝牙未开启或不可用，请在系统设置中开启')), 
      );
      return false;
    }
  }

  void _startScan() async {
    // 在扫描前，确保权限与适配器状态就绪
    final ready = await _ensurePermissionsAndBluetoothOn();
    if (!ready) {
      return;
    }

    // 清除之前的结果
    scanResults.clear();

    // 开始扫描
    setState(() {
      isScanning = true;
    });

    try {
      // 订阅扫描结果，打印名称/ID/RSSI，过滤仅显示有名称设备
      scanSubscription = FlutterBluePlus.scanResults.listen((results) {
        final filteredResults = results.where((r) => r.device.name.isNotEmpty).toList();
        setState(() {
          scanResults = filteredResults;
        });
        for (final r in filteredResults) {
          debugPrint('[BLE] Found: name=${r.device.name}, id=${r.device.id}, rssi=${r.rssi}');
        }
        debugPrint('[BLE] Total named devices: ${filteredResults.length}');
      });

      await FlutterBluePlus.startScan(timeout: const Duration(seconds: 30));

      setState(() {
        isScanning = false;
      });
    } catch (e) {
      debugPrint('[BLE] 扫描错误: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('扫描失败: $e')),
      );
      setState(() {
        isScanning = false;
      });
    }
  }

  void _stopScan() async {
    await FlutterBluePlus.stopScan();
    await scanSubscription?.cancel();
    setState(() {
      isScanning = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Calendar'),
        actions: [
          IconButton(
            icon: isScanning
                ? const Icon(Icons.stop)
                : const Icon(Icons.search),
            onPressed: isScanning ? _stopScan : _startScan,
          ),
        ],
      ),
      body: Stack(
        children: [
          // 实时显示设备列表
          ListView.separated(
            itemCount: scanResults.length,
            separatorBuilder: (context, index) => const Divider(),
            itemBuilder: (context, index) {
              final result = scanResults[index];
              return ListTile(
                title: Text(result.device.name),
                subtitle: Text(result.device.id.toString()),
                trailing: Text('信号强度: ${result.rssi} dBm'),
                onTap: () {
                  _stopScan();
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) =>
                          DeviceDetailPage(device: result.device),
                    ),
                  );
                },
              );
            },
          ),
          // 扫描中指示器
          if (isScanning)
            Positioned(
              top: 16,
              left: 16,
              right: 16,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: Colors.blue.withOpacity(0.9),
                  borderRadius: BorderRadius.circular(20),
                ),
                child: const Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    SizedBox(
                      width: 16,
                      height: 16,
                      child: CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 2,
                      ),
                    ),
                    SizedBox(width: 8),
                    Text(
                      '正在扫描...',
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
          // 空状态提示
          if (!isScanning && scanResults.isEmpty)
            const Center(
              child: Text('未发现设备，请点击右下角按钮开始扫描'),
            ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _startScan,
        tooltip: '扫描设备',
        child: const Icon(Icons.bluetooth_searching),
      ),
    );
  }
}